//
//  XHomeSegementView.m
//  Bees
//
//  Created by Xiaohan on 2018/12/18.
//  Copyright © 2018 xiaohan. All rights reserved.
//

#import "XHomeSegementView.h"
static NSInteger const kSegementBtnTag = 987;
@implementation XHomeSegementView

- (void)setSelIndex:(NSInteger)selIndex{
    _selIndex = selIndex;
    UIButton *button = [_segementView viewWithTag:kSegementBtnTag+selIndex];
    if (button) {
        [self didClickButton:button];
    }
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self segementPageSetting];
    }
    return self;
}

- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
//        [KPostNotificationCenter addObserver:self selector:@selector(didClickNoti:) name:kXHomePageScrollOffsetChangeNoti object:nil];
        [self segementPageSetting];
    }
    return self;
}
- (void)layoutSubviews{
    if (_fixedWidth>0) {
        _segementView.frame = self.bounds;
    }else{
        ///应UI需求 加间隙
        _segementView.frame = CGRectMake(kNormalSpace, 0, self.width-2*kNormalSpace, self.height);
    }
    self.contentView.frame = self.bounds;
}
- (void)didClickNoti:(NSNotification*)noti{
    NSNumber *number = noti.object;
    UIButton*clickBtn = [_segementView viewWithTag:kSegementBtnTag+number.integerValue];
    if (clickBtn) {
        [self didClickButton:clickBtn];
    }
}
- (void)segementPageSetting {
    self.contentView.backgroundColor = UIColor.whiteColor;
    _segementHeight = KHomeSegementHeight;
    _indicateHeight = 3.0f;
    _widthArr = [NSMutableArray array];
    _segementView = [[UIScrollView alloc] initWithFrame:self.bounds];
    _segementView.backgroundColor = UIColor.whiteColor;
    _segementView.showsHorizontalScrollIndicator = NO;
    _segementView.showsVerticalScrollIndicator = NO;
    _segementView.bounces = NO;
    [self.contentView addSubview:_segementView];
    _indicateView = [[UIView alloc] init];
    _indicateView.backgroundColor = UIColorHex(#FFCC03);
}
- (void)setTitles:(NSArray *)titles{
    if ([_titles isEqualToArray:titles]) {
        return;
    }
    _selectedButton = nil;
    _titles = titles;
    [_widthArr removeAllObjects];
    [_segementView removeAllSubviews];
    [self.segementView setContentOffset:CGPointMake(0, 0) animated:NO];
    CGFloat item_x = 0;
    for (int i = 0; i < _titles.count; i++) {
        NSString *title = _titles[i];
        CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName:kBoldFont(AdaptedFontSize(17))}];
        UIButton *button = [_segementView viewWithTag:kSegementBtnTag+i];
        if (!button) {
            button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setTag:kSegementBtnTag+i];
            button.titleLabel.font= kBoldFont(17);
            [button setTitleColor:UIColorHex(#B5B5B5) forState:UIControlStateNormal];
            [button setTitleColor:UIColorHex(#000000) forState:UIControlStateSelected];
            [button addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
            [_segementView addSubview:button];
        }
        if (_fixedWidth>0) {
            button.frame = CGRectMake(item_x, 0, _fixedWidth, _segementHeight);
        }else{
            button.frame = CGRectMake(item_x, 0, titleSize.width, _segementHeight);
        }

        [button setTitle:title forState:UIControlStateNormal];
        [_widthArr addObject:[NSNumber numberWithDouble:CGRectGetWidth(button.frame)]];
        if (_fixedWidth  > 0) {
            item_x += _fixedWidth;
        }else{
            item_x += AdaptedWidth(10) + titleSize.width;
        }
        
        if  (!_selectedButton && (i == 0)) {
            button.selected = YES;
            _selectedButton = button;
            // 添加指示杆
            if (!_indicateView) {
                _indicateView = [[UIView alloc] init];
                _indicateView.backgroundColor = UIColorHex(#FFCC03);
            }
            _indicateView.frame = CGRectMake((button.width-titleSize.width)*.5, _segementHeight - _indicateHeight-8, titleSize.width, _indicateHeight);
            [_segementView addSubview:_indicateView];
        }
    }
    self.segementView.contentSize = CGSizeMake(item_x, _segementHeight);
    self.width = item_x;
}
#pragma mark -- 按钮方法

- (void)didClickButton:(UIButton *)button {
    if (button != _selectedButton) {
//        KPostNotification(kXHomePageSegementChangeNoti, @(button.tag-kSegementBtnTag));
        button.selected = YES;
        _selectedButton.selected = !_selectedButton.selected;
        _selectedButton = button;
        [self scrollIndicateView];
        [self scrollSegementView];
    }
    
    if (_resultBlock) {
        _resultBlock(_selectedButton.tag-kSegementBtnTag);
    }
}

/**
 根据选中的按钮滑动指示杆
 */
- (void)scrollIndicateView {
//    NSInteger index = [self selectedAtIndex];
    CGSize titleSize = [_selectedButton.titleLabel.text sizeWithAttributes:@{NSFontAttributeName : kBoldFont(16)}];
    [UIView animateWithDuration:0.2f delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self->_indicateView.frame = CGRectMake(CGRectGetMinX(self->_selectedButton.frame) + (self->_selectedButton.width-titleSize.width)*.5, CGRectGetMinY(self->_indicateView.frame), titleSize.width, self->_indicateHeight);
    } completion:^(BOOL finished) {
    }];
}

/**
 根据选中调整segementView的offset
 */
- (void)scrollSegementView {
    // 计算偏移量
    CGFloat offsetX = _selectedButton.centerX - self.width * 0.5;
    // 获取最大滚动范围
    CGFloat maxOffsetX = _segementView.contentSize.width - self.width;
    if (offsetX > maxOffsetX){
        DLog(@"maxOffsetX %f",maxOffsetX);
       offsetX = maxOffsetX;
    }
    if (offsetX < 0) {
        offsetX = 0;
    }
    // 滚动标题滚动条
    [_segementView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}
#pragma mark -- index

- (NSInteger)selectedAtIndex {
    return _selectedButton.tag;
}

- (void)setSelectedItemAtIndex:(NSInteger)index {
    for (UIView *view in _segementView.subviews) {
        if ([view isKindOfClass:[UIButton class]] && view.tag == index) {
            UIButton *button = (UIButton *)view;
            [self didClickButton:button];
        }
    }
}

- (CGFloat)widthAtIndex:(NSInteger)index {
    if (index < 0 || index > _titles.count - 1) {
        return .0;
    }
    return [[_widthArr objectAtIndex:index] doubleValue];
}

- (void)dealloc{
//    [KPostNotificationCenter removeObserver:self];
}
@end



@implementation XHomeTipHeadView

- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI{
        self.contentView.backgroundColor = UIColor.whiteColor;
        self.titleLab = [UILabel new];
        self.titleLab.font = kBoldFont(20);
        UIView*bottomV = [UIView new];
        bottomV.alpha = .5f;
        bottomV.backgroundColor = UIColorHex(#FFF100);
        [self.contentView addSubview:bottomV];
        [self.contentView addSubview:self.titleLab];
        [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(kNormalSpace);
            make.centerY.mas_equalTo(0);
        }];
        //        [tipLab setLayerShadow:UIColorHex(#FFF100) offset:CGSizeMake(0, 6) radius:3];
        [bottomV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.titleLab.mas_left);
        make.right.equalTo(self.titleLab.mas_right);
        make.bottom.equalTo(self.titleLab.mas_bottom);
        make.height.mas_equalTo(AdaptedWidth(10.0f));
        }];
}

@end



